package com.easyidea.its.web.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.easyidea.its.facade.tracklog.TrackLogMgr;
import com.easyidea.its.util.ExportExcel;
import com.easyidea.its.util.ItsConstants;
import com.easyidea.its.util.excel.ExportDataUtil;
import com.easyidea.its.web.dto.SeesionUserDto;
import com.easyidea.its.web.dto.StatisticsDto;
import com.easyidea.its.web.dto.StatisticsExport;

/**
 * @author leno 使用servlet导出动态生成的excel文件，数据可以来源于数据库
 *         这样，浏览器客户端就可以访问该servlet得到一份用java代码动态生成的excel文件
 */
public class ExportTrackLog extends javax.servlet.http.HttpServlet {
	static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("octets/stream");
		response.setContentType("text/xml;charset=UTF-8");

		String fileName = java.net.URLEncoder.encode("统计数据","UTF8") + ".xls";
		response.addHeader("Content-Disposition", "attachment;filename="+fileName);
		ExportExcel<StatisticsExport> ex = new ExportExcel<StatisticsExport>();
		String[] headers = { "过车流量", "统计时间" };
		SeesionUserDto dto = (SeesionUserDto) request.getSession()
				.getAttribute(ItsConstants.SESSION_KEY_USER_INFO);
		WebApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(this.getServletContext());
		try {
			TrackLogMgr trackLogMgr = (TrackLogMgr) context
					.getBean("trackLogMgr");
			List<StatisticsExport> dataset = new ArrayList<StatisticsExport>();
			if (request.getSession().getAttribute(
					dto.getUserId() + "."
							+ ItsConstants.SESSION_KEY_STATISTICS_DTO) != null) {
				StatisticsDto statisticsDto = (StatisticsDto) request
						.getSession().getAttribute(
								dto.getUserId() + "."
										+ ItsConstants.SESSION_KEY_STATISTICS_DTO);
				Collection<Object[]> objs = trackLogMgr.statisticsByCondition(statisticsDto);
				dataset = ExportDataUtil.createDataset(statisticsDto, objs);
			}
			OutputStream out = response.getOutputStream();
			ex.exportExcel(headers, dataset, out);
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	public static String toUtf8String(String s) {

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			}

			else {

				byte[] b;

				try {
					b = Character.toString(c).getBytes("utf-8");
				}

				catch (Exception ex) {

					System.out.println(ex);

					b = new byte[0];

				}

				for (int j = 0; j < b.length; j++) {

					int k = b[j];

					if (k < 0)
						k += 256;

					sb.append(" % " + Integer.toHexString(k).toUpperCase());

				}

			}

		}

		return sb.toString();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}